Solution: Write Code with WaitGroup
Check the solution to the challenge of writing code using WaitGroup.
We'll cover the following
Problem statement#
Let’s walk through the solution step by step. Using the http package, we can make the homepage API. Once we hit the API, it will redirect to the homeHandler function. The homeHandler function will create multiple goroutines, and each goroutine will call the fetch function that makes the necessary GET call on the URL and receives the response status.
Let’s look at the handleRequests function. The http package provides the necessary HandleFunc function for routing and the ListenAndServe function to listen on the specific port number.
Now let’s look at the implementation of the homeHandler function below:
- Loop over the list of
urls.
-
Wait for goroutines before printing anything to the screen using
wg.Wait() -
Complete the wait function once the goroutines finish their execution using
defer wg.Done()
We add it all together in the code block below:
In order to print the message to the screen, use the Fprintf function, which takes responseWriter and the message to print.
Another function, which makes the GET call, receives the response status. The http.get(url) will return the error and response. It also decreases the wait counter once it is done with the function.
Code walkthrough#
Let’s walk through the code.
/
Explanation#
The important lines in the code are explained below:
- Line 26: We call the
Donemethod to decrement the counter. - Line 37: We instruct the main goroutine to wait for the
len(URLs)and get the response status. - Line 41: We wait until we receive the response from all the URLs.
- Lines 46–47: We create the API endpoint and port.
Why to use WaitGroup?#
Why is the WaitGroup necessary when making a few HTTP requests to get the status?
Suppose we are making 100 calls, and each call may take up to five seconds. If we don’t use WaitGroup, our function will print that we have successfully received all the responses even before we’ve received the responses from all the HTTP requests.
/
Suppose we want to perform an operation before moving to a specific line of the code. Without WaitGroup, it won’t be possible for us to ensure that all the goroutines return the response.
Challenge: Write Code with WaitGroup
Quiz